<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>系统设置</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <!-- 首页轮播图配置 -->
        <el-divider content-position="left">首页配置</el-divider>

        <el-form-item label="首页轮播图" prop="imagePath">
          <!-- <imageUpload
            v-model="form.imagePath"
            :limit="5"
            :return-url="true"
          /> -->
           <media-upload v-model="form.imagePath" :limit="5" :return-url="true" @change="handleMediaChange" />
          <div class="form-tip">最多可上传5张轮播图</div>
        </el-form-item>
        <el-form-item label="活动广告图" prop="adList">
          <media-upload v-model="form.adList" :limit="5" :return-url="true" @change="handleMediaChange" />
          <div class="form-tip">最多可上传5张轮播图</div>
        </el-form-item>

        <!-- 新增限时特价日期字段 -->
        <el-form-item label="限时特价日期" prop="limitTime">
          <el-date-picker
            v-model="form.limitTime"
            type="datetime"
            placeholder="选择限时特价截止时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
          <div class="form-tip">设置限时特价的截止时间</div>
        </el-form-item>

        <el-form-item label="首页通知消息" prop="notice">
          <div class="notice-list">
            <div
              v-for="(notice, index) in noticeList"
              :key="index"
              class="notice-item"
            >
              <el-input
                v-model="noticeList[index]"
                placeholder="请输入通知消息"
                class="notice-input"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeNotice(index)"
                class="notice-delete-btn"
              ></el-button>
            </div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addNotice"
              class="add-notice-btn"
            >
              添加通知消息
            </el-button>
          </div>
        </el-form-item>

        <!-- 我的页面配置 -->
        <el-divider content-position="left">我的页面配置</el-divider>

        <el-form-item label="客服电话" prop="customerService">
          <el-input
            v-model="form.customerService"
            placeholder="请输入客服电话号码"
            maxlength="20"
          />
          <div class="form-tip">请输入有效的客服电话号码</div>
        </el-form-item>

        <!-- 关于我们配置 -->
        <el-divider content-position="left">关于我们配置</el-divider>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="form.company" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司英文名称" prop="companyEnglish">
              <el-input v-model="form.companyEnglish" placeholder="请输入公司英文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品定位" prop="productPositioning">
              <el-input v-model="form.productPositioning" placeholder="请输入产品定位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公司介绍" prop="companyIntroduction">
          <el-input
            v-model="form.companyIntroduction"
            type="textarea"
            :rows="4"
            placeholder="请输入公司介绍"
          />
        </el-form-item>

        <el-form-item label="企业文化" prop="corporateCulture">
          <el-input
            v-model="form.corporateCulture"
            type="textarea"
            :rows="4"
            placeholder="请输入企业文化"
          />
        </el-form-item>

        <el-form-item label="企业品牌" prop="enterpriseBrand">
          <el-input
            v-model="form.enterpriseBrand"
            type="textarea"
            :rows="3"
            placeholder="请输入企业品牌信息"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业认证1" prop="enterpriseCertification1">
              <el-input v-model="form.enterpriseCertification1" placeholder="请输入企业认证信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业认证2" prop="enterpriseCertification2">
              <MediaUpload
                v-model="form.enterpriseCertification2"
                :limit="1"
                :return-url="true"
              />
              <div class="form-tip">可上传图片或视频，最多1个文件</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 积分配置 -->
        <el-divider content-position="left">积分配置</el-divider>

        <el-form-item label="积分规则" prop="scoreDesc">
          <el-input
            v-model="form.scoreDesc"
            type="textarea"
            :rows="4"
            placeholder="请输入积分规则说明"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="兑换比例" prop="rate">
              <el-input-number
                v-model="form.rate"
                :precision="2"
                :min="0"
                placeholder="请输入金额和积分兑换比例"
                style="width: 100%"
              />
              <div class="form-tip">1元 = ? 积分</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存设置</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { listConfig, updateConfig ,getConfig,addConfig} from "@/api/config";
import imageUpload from "@/components/ImageUpload";
import MediaUpload from "@/components/MediaUpload";

export default {
  name: "Setting",
  components: {
    imageUpload,
    MediaUpload
  },
  data() {
    return {
      // 加载状态
      loading: false,
      // 提交状态
      submitLoading: false,
      // 通知消息列表
      noticeList: [''],
      // 表单数据
      form: {
        id: undefined,
        imagePath: '',
        adList: undefined,
        limitTime: null, // 限时特价截止时间
        notice: '',
        customerService: '',
        company: '',
        companyIntroduction: '',
        productPositioning: '',
        corporateCulture: '',
        enterpriseBrand: '',
        enterpriseCertification1: '',
        enterpriseCertification2: '',
        scoreDesc: '',
        rate: 0,
        remark: ''
      },
      // 表单校验规则
      rules: {
        // limitTime: [
        //   { type: 'date', message: "请选择限时特价截止时间", trigger: "change" }
        // ]
    //     company: [
    //       { required: true, message: "公司名称不能为空", trigger: "blur" }
    //     ],
    //     customerService: [
    //       { pattern: /^[0-9-+()\s]+$/, message: "请输入有效的电话号码", trigger: "blur" }
    //     ],
    //     rate: [
    //       { required: true, message: "兑换比例不能为空", trigger: "blur" },
    //       { type: 'number', min: 0, message: "兑换比例必须大于等于0", trigger: "blur" }
    //     ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 媒体变化处理
    handleMediaChange(mediaList) {
      console.log('轮播图媒体变化:', mediaList);
      // 可以在这里处理媒体变化的逻辑
    },
    /** 获取系统设置数据 */
    async getList() {
      this.loading = true;
      try {
        const response = await listConfig();
        console.log("response --- ",response)
        // 获取数组中的第一个数据
        const data = response.rows && response.rows.length > 0 ? response.rows[0] : {};

        this.form = {
          id: data.id || undefined,
          imagePath: data.imagePath || '',
          adList: data.adList || "",
          limitTime: data.limitTime || null, // 直接赋值单个时间点
          notice: data.notice || '',
          customerService: data.customerService || '',
          company: data.company || '',
          companyIntroduction: data.companyIntroduction || '',
          productPositioning: data.productPositioning || '',
          corporateCulture: data.corporateCulture || '',
          enterpriseBrand: data.enterpriseBrand || '',
          enterpriseCertification1: data.enterpriseCertification1 || '',
          enterpriseCertification2: data.enterpriseCertification2 || '',
          scoreDesc: data.scoreDesc || '',
          rate: data.rate || 0,
          remark: data.remark || ''
        };

        // 处理通知消息列表
        this.parseNoticeList(data.notice);

      } catch (error) {
        console.error('获取系统设置失败:', error);
        this.$modal.msgError("获取系统设置失败");
      } finally {
        this.loading = false;
      }
    },

    /** 解析通知消息为列表 */
    parseNoticeList(noticeData) {
      if (noticeData) {
        try {
          // 尝试解析JSON数组格式
          if (typeof noticeData === 'string') {
            const parsed = JSON.parse(noticeData);
            if (Array.isArray(parsed)) {
              this.noticeList = parsed.filter(item => item && item.trim()).map(item => item.trim());
            } else {
              // 如果不是数组，按原来的分号分割方式处理（兼容旧数据）
              this.noticeList = noticeData.split(/[\n;]/).filter(item => item.trim()).map(item => item.trim());
            }
          } else if (Array.isArray(noticeData)) {
            // 如果已经是数组格式
            this.noticeList = noticeData.filter(item => item && item.trim()).map(item => item.trim());
          } else {
            this.noticeList = [''];
          }

          if (this.noticeList.length === 0) {
            this.noticeList = [''];
          }
        } catch (error) {
          console.warn('解析通知数据失败，使用默认格式:', error);
          // 解析失败时按字符串分割处理（兼容旧数据）
          if (typeof noticeData === 'string') {
            this.noticeList = noticeData.split(/[\n;]/).filter(item => item.trim()).map(item => item.trim());
          }
          if (this.noticeList.length === 0) {
            this.noticeList = [''];
          }
        }
      } else {
        this.noticeList = [''];
      }
    },

    /** 格式化通知消息列表为JSON数组 */
    formatNoticeList() {
      const filteredList = this.noticeList.filter(item => item && item.trim());
      return JSON.stringify(filteredList);
    },

    /** 添加通知消息 */
    addNotice() {
      this.noticeList.push('');
    },

    /** 删除通知消息 */
    removeNotice(index) {
      if (this.noticeList.length > 1) {
        this.noticeList.splice(index, 1);
      } else {
        this.$modal.msgWarning("至少保留一条通知消息");
      }
    },

    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 格式化通知消息为字符串
            const submitData = {
              ...this.form,
              notice: this.formatNoticeList()
            };
            if (this.form.id != undefined) {
              await updateConfig(submitData);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addConfig(submitData);
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          } catch (error) {
            console.error('提交失败:', error);
            this.$modal.msgError("操作失败");
          }finally {
            this.submitLoading = false;
          }
        }
      });
    },

    /** 重置表单 */
    resetForm() {
      this.$refs["form"].resetFields();
      this.noticeList = [''];
      this.getList();
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-divider {
  margin: 30px 0 20px 0;
}

.el-divider:first-of-type {
  margin-top: 0;
}

.box-card {
  margin: 20px;
}

/* 通知消息列表样式 */
.notice-list {
  width: 100%;
}

.notice-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.notice-input {
  flex: 1;
  margin-right: 10px;
}

.notice-delete-btn {
  flex-shrink: 0;
}

.add-notice-btn {
  margin-top: 5px;
}
</style>
